package com.hiwhitley.chapter05;

/**
 * Created by hiwhitley on 17-1-13.
 */
public class Replace {
    public String replace(String str, String from, String to) {
        if (str == null || from == null || str.equals("") || from.equals("")) {
            return str;
        }

        char[] chas = str.toCharArray();
        char[] chaf = from.toCharArray();
        int match = 0;
        for (int i = 0; i < chas.length; i++) {
            if (chas[i] == chaf[match++]) {
                if (match == chaf.length) {
                    clear(chas, i, chaf.length);
                    match = 0;
                }
            } else {
                match = 0;
            }
        }

        String res = "";
        String cur = "";
        for (int i = 0; i < chas.length; i++) {
            if (chas[i] != 0) {
                cur = cur + String.valueOf(chas[i]);
            }

            if (chas[i] == 0 && (i == 0 || chas[i - 1] != 0)) {
                res = res + cur + to;
                cur = "";
            }
        }
        if (!cur.equals("")) {
            res = res + cur;
        }
        return res;
    }

    public void clear(char[] chars, int end, int len) {
        while (len-- != 0) {
            chars[end--] = 0;
        }
    }

    public static void main(String[] args) {
        Replace replace = new Replace();
        System.out.println(replace.replace("123abc123abc", "abc", "X"));
    }
}
